package com.nursinghome.common.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.nursinghome.bean.Goods;
import com.nursinghome.bean.Order;
import com.nursinghome.bean.OrderDetail;
import com.nursinghome.bean.OrderVo;
import com.nursinghome.common.mapper.OrderMapper;
import com.nursinghome.common.service.GoodsService;
import com.nursinghome.common.service.OrderDetailService;
import com.nursinghome.common.service.OrderService;
import com.nursinghome.exception.NurisingHomeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 程硕
* @createDate 2025-04-07 01:10:32
*/
@Service
public class OrderServiceImpl implements OrderService{
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderDetailService orderDetailService;

    /*
    * 生成雪花算法的id
    * 生成对应的订单详细
    * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insert(OrderVo orderVo) throws NurisingHomeException {
        // 算法算法生成唯一id 1910337022447456256
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        String id = snowflake.nextIdStr();
        Long eid = orderVo.getEid();
        // 计算总金额
        List<HashMap<Integer, Integer>> goodsIds = orderVo.getGoodsIds();
        BigDecimal totalAmount = new BigDecimal(0);
        for (HashMap<Integer, Integer> goodsId : goodsIds) {
            for (Map.Entry<Integer, Integer> entry : goodsId.entrySet()) {
                Integer gid = entry.getKey();
                Integer count = entry.getValue();
                Goods goods = goodsService.selectById(gid);
                totalAmount = totalAmount.add(goods.getPrice().multiply(new BigDecimal(count)));
            }
        }
        // 生成订单详情
        for (HashMap<Integer, Integer> goodsId : goodsIds) {
            for (Map.Entry<Integer, Integer> entry : goodsId.entrySet()) {
                Integer gid = entry.getKey();   // 菜品ID，如 1
                Integer count = entry.getValue(); // 数量，如 1

                Goods goods = goodsService.selectById(gid);

                if (goods.getCount() < count) {
                    throw new NurisingHomeException("商品库存不足");
                } else {
                    goods.setCount(goods.getCount() - count);
                    goodsService.updateByCount(goods);
                }

                orderDetailService.insert(
                        new OrderDetail(null, id, goods.getId(), count, goods.getPrice().multiply(new BigDecimal(count)), 1, null, null)
                );
            }
        }
        Order order = new Order();
        order.setId(id);
        order.setEid(eid);
        order.setCreateTime(DateUtil.date());
        order.setUpdateTime(DateUtil.date());
        order.setTotalAmount(totalAmount);
        order.setPayType(0);
        order.setStatus(1);
        order.setIsDelete(1);
        order.setDate(orderVo.getDate());

        return orderMapper.insert(order) > 0;
    }

    @Override
    public Boolean update(Order order) throws NurisingHomeException {
        // 查询订单是否存在
        Order orderOld = orderMapper.selectById(order.getId());
        if (orderOld == null){
            throw new NurisingHomeException("订单不存在");
        }
        return orderMapper.update(order) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(String id) throws NurisingHomeException {
        // 查询订单是否存在
        Order orderOld = orderMapper.selectById(id);
        if (orderOld == null){
            throw new NurisingHomeException("订单不存在");
        }
        // 删除订单详细
        if (orderDetailService.deleteByOrderId(id)) {
            throw new NurisingHomeException("订单详细删除失败");
        }
        return orderMapper.delete(id) > 0;
    }

    @Override
    public Order selectById(String id) {
        return orderMapper.selectById(id);
    }

    @Override
    public List<Order> selectAll() {
        return orderMapper.selectAll(new Order());
    }

    @Override
    public List<Order> selectByCondition(Order order) {
        return orderMapper.selectAll(order);
    }
}
